package com.ebrothers.isns;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.ebrothers.isns.common.JsonConverter;
import com.ebrothers.isns.common.Params;
import com.ebrothers.isns.dao.DAOException;
import com.ebrothers.isns.dao.QuestionDAO;
import com.ebrothers.isns.vo.Question;

/**
 * Servlet implementation class ListQuestions
 */
public class ListQuestions extends HttpServlet {
	private static final Logger logger = Logger.getLogger(ListQuestions.class);
	private static final long serialVersionUID = 1L;

	private QuestionDAO questionDAO;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ListQuestions() {
		super();
		questionDAO = new QuestionDAO();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String qDate = request.getParameter(Params.Q_DATE);
		logger.info("[ListQuestions] qDate=" + qDate);
		if (qDate != null) {
			List<Question> questions;
			try {
				questions = questionDAO.getQuestionsByDate(qDate);
				String json = JsonConverter.beansToJson(questions);
				logger.info("[ListQuestions] result=" + json);
				ServletOutputStream out = response.getOutputStream();
				out.write(json.getBytes("utf-8"));
				out.flush();
				out.close();
			} catch (DAOException e) {
				logger.error("GOT AN ERROR!", e);
				throw new ServletException(e);
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
